/**
 * 固收权益页面
 * @author gf
 */
import React, { useEffect, useState, useSyncExternalStore } from "react";
import styles from "./index.less";
import cn from "classnames";
import FofButton from "@/components/Button/fofButton";
import LittleTitle from "@/components/Title/littleTitle";
import StackBar from "@/components/EchartsComponents/Bar/stackBar";
import { Empty, Table } from "antd";
import * as _ from "lodash";
import {
  find_by_portfolio_code,
  fund_credit_dept_industry_rate,
  queryInvestRatio,
  fund_city_investment_province_rate,
  weighting_duration,
  find_convertible_bond_by_portfolio_code,
} from "./fixedAssets";
import Pie from "@/components/EchartsComponents/Pie/pie";
import MultiLine from "@/components/EchartsComponents/Line/MultiLine";
import { PageWrapper } from "@/components/PageWrapper";
import { Title } from "@/components/Title";
import { getUrlParam } from "@/utils/utils";
import { fof_portfolio_basic } from "../PortfolioOverview/portfolio";
import { PROVINCE_CODE_JSON } from "@/utils/const";
import { getBaseColors } from "@/utils/echarts";
import EventEmpty from "@/components/FOF/EventEmpty";
import { EBox } from "../OverAllFeature";

const portfolioCode = getUrlParam("id");

export const RenderDesc = (props: any) => {
  const [info, setInfo] = useState<any>({});

  useEffect(() => {
    fof_portfolio_basic({ portfolioCode }).then((res) => {
      if (res?.code === "0") {
        setInfo(res?.data);
      }
    });
  }, [portfolioCode]);
  return (
    <div
      className={cn(styles.boxBorder, styles.renderdesc, styles.mt12)}
      style={{ borderRadius: 2 }}
    >
      <FofButton text={info?.portfolioName || "-"} className={styles.title} />
      <div className={styles.footer}>
        <div className={styles.footer_date}>
          <span>组合成立时间</span>
          <span>{info?.establishDate || "-"}</span>
        </div>
        <div className={styles.footer_date}>
          <span>数据更新时间</span>
          <span>{info?.dataUpdateDate || "-"}</span>
        </div>
        <div className={styles.footer_date}>
          <span>最新点评时间</span>
          <span>{info?.commentDate || "-"}</span>
        </div>
      </div>
    </div>
  );
};

const _renderText = (text, record, dataIndex) => {
  return record[dataIndex] ? (_.isNumber(text) ? text : "-") : null;
};

const FixedAssets = (props: any) => {
  // console.log(props)
  // const detailState = useSelector(s => s.holderDetail)
  // const { detailList } = detailState
  const [creditList, setCreditList] = useState([]);
  const [creditPieData, setCreditPieData] = useState([]);
  const [areaPieData, setAreaPieData] = useState([]);
  const [areaList, setAreaList] = useState([]);
  const [detailList, setDetailList] = useState([]);
  const [convertList, setConvertList] = useState([]);
  const [bondRatio, setBondRatio] = useState();
  const [bondLegend, setBondLegend] = useState([]);
  const [bondAxis, setBondAxis] = useState([]);

  const [weightList, stWeightList] = useState([]);
  const [weightLine, setWeightLine] = useState<any>({});

  // const dispatch = useDispatch()
  // const _select = useSelector()
  // console.log(detailState);

  // const handleQueryHolderDetail = () => {
  //   dispatch({
  //     type: 'HOLDER_DETAIL',
  //     payload: {
  //       "portfolioCode": "1"
  //     }
  //   })
  // }

  useEffect(() => {
    // handleQueryHolderDetail()
    find_by_portfolio_code({ portfolioCode }).then((res) => {
      if (res?.code === "0") {
        setDetailList(res?.data || []);
      }
    });
    fund_credit_dept_industry_rate({ portfolioCode }).then((res) => {
      if (res?.code === "0") {
        setCreditList(res?.data || []);
        if (!_.isEmpty(res?.data)) {
          const a = [];
          res.data.forEach((r) => {
            a.push({
              name: r.firstIndustryName,
              value: r.ratioInNv,
            });
          });
          setCreditPieData(a);
        }
      }
    });
    fund_city_investment_province_rate({ portfolioCode }).then((res) => {
      if (res?.code === "0") {
        setAreaList(res?.data || []);
        if (!_.isEmpty(res?.data)) {
          const a = [];
          res.data.forEach((r) => {
            a.push({
              name:
                r.provinceName || PROVINCE_CODE_JSON[r.provinceCode + "0000"],
              value: r.ratioInNv,
            });
          });
          setAreaPieData(a);
        }
      }
    });
    queryInvestRatio({ portfolioCode }).then((res) => {
      if (res?.code === "0") {
        if (!_.isEmpty(res?.data?.yaxis)) {
          setBondRatio(res?.data?.yaxis || []);
          const legend = res?.data?.yaxis.map((v) => v.label);
          setBondLegend(legend || []);
          setBondAxis(res?.data.xaxis || []);
        }
      }
    });
    weighting_duration({ portfolioCode }).then((res) => {
      if (res?.code === "0") {
        stWeightList(res?.data?.weightingDurationList || []);
        setWeightLine(res?.data?.axis || {});
      }
    });
    find_convertible_bond_by_portfolio_code({ portfolioCode }).then((res) => {
      if (res?.code === "0") {
        setConvertList(res?.data);
      }
    });
  }, []);

  const detailColumns: any = [
    {
      title: "序号",
      dataIndex: "order",
      key: "order",
      width: 50,
      render: (text, records, index) => (
        <span
          style={{
            textAlign: "center",
            display: "inline-block",
            width: "100%",
          }}
        >
          {index + 1}
        </span>
      ),
    },
    {
      title: "债券代码",
      dataIndex: "bondInnerCode",
      key: "bondInnerCode",
      // width: 110,
      ellipsis: true,
      render: (text) => text || "-",
    },
    {
      title: "债券名称",
      dataIndex: "bondName",
      key: "bondName",
      // width: 120,
      ellipsis: true,
      render: (text) => text || "-",
    },
    {
      title: "券种",
      dataIndex: "bondType",
      key: "bondType",
      // width: 120,
      ellipsis: true,
      render: (text) => text || "-",
    },
    {
      title: "申万行业",
      dataIndex: "shenwanFirstIndustryName",
      key: "shenwanFirstIndustryName",
      // width: 70,
      render: (text) => text || "-",
    },
    {
      title: "主体最新信用评级",
      dataIndex: "modelRankValue",
      key: "modelRankValue",
      // width: 130,
      render: (text) => text || "-",
    },
    {
      title: "债项评级",
      dataIndex: "bondDebtLevel",
      key: "bondDebtLevel",
      // width: 70,
      render: (text) => text || "-",
    },
    {
      title: "占基金组合资产净值比例(％)",
      dataIndex: "rate",
      key: "rate",
      // width: 190,
      align:'right',
      render: (text) => (_.isNumber(text) ? text : text || "-"),
    },
    {
      title: "持有该债券的基金",
      dataIndex: "holdBondFundList",
      key: "holdBondFundList",
      // width: 180,
      ellipsis: true,
      render: (text) => {
        let str = "";
        if (!_.isEmpty(text)) {
          text.forEach((v, i) => {
            str =
              str +
              (v.fundName || "-") +
              `(${v.fundSecuCode || "-"})` +
              (i === text.length - 1 ? "" : ",");
          });
        }
        return str || "-";
      },
    },
  ];

  const detailColumnsConvert: any = [
    {
      title: "序号",
      dataIndex: "order",
      key: "order",
      width: 50,
      render: (text, records, index) => (
        <span
          style={{
            textAlign: "center",
            display: "inline-block",
            width: "100%",
          }}
        >
          {index + 1}
        </span>
      ),
    },
    {
      title: "债券代码",
      dataIndex: "bondInnerCode",
      key: "bondInnerCode",
      // width: 80,
      ellipsis: true,
      render: (text) => text || "-",
    },
    {
      title: "债券名称",
      dataIndex: "bondName",
      key: "bondName",
      // width: 80,
      ellipsis: true,
      render: (text) => text || "-",
    },
    {
      title: "正股名称",
      dataIndex: "secuAbbr",
      key: "secuAbbr",
      // width: 80,
      ellipsis: true,
      render: (text) => text || "-",
    },
    {
      title: "转债类型",
      dataIndex: "bondType",
      key: "bondType",
      // width: 80,
      ellipsis: true,
      render: (text) => text || "-",
    },
    {
      title: "主体/债项评级",
      dataIndex: "bondName",
      key: "bondName",
      // width: 140,
      ellipsis: true,
      render: (text, record: any) =>
        `${record.crAsCode || "-"}/${record.latestExternalRating || "-"}(${
          record.crAsCodeComp || '-'
        }/${record.latestExternalRatingComp || '-'})`,
    },
    {
      title: "当前转股价格（元）",
      dataIndex: "ConvertPrice",
      key: "ConvertPrice",
      width: 140,
      ellipsis: true,
      align:'right',
      render: (text) => text || "-",
    },
    {
      title: "纯债价值",
      dataIndex: "CBStrbValue",
      key: "CBStrbValue",
      // width: 70,
      ellipsis: true,
      align:'right',
      render: (text) => text || "-",
    },
    {
      title: "转股价值",
      dataIndex: "CBConvertValue",
      key: "CBConvertValue",
      // width: 130,
      ellipsis: true,
      align:'right',
      render: (text) => text || "-",
    },
    {
      title: "纯债溢价率(％)",
      dataIndex: "CBStrbPremiumRatio",
      key: "CBStrbPremiumRatio",
      // width: 120,
      ellipsis: true,
      align:'right',
      render: (text) => text || "-",
    },
    {
      title: "转股溢价率 (％)",
      dataIndex: "ConvertPremiumRate",
      key: "ConvertPremiumRate",
      // width: 120,
      ellipsis: true,
      align:'right',
      render: (text) => (_.isNumber(text) ? text : text || "-"),
    },
    {
      title: "占基金组合资产净值比例(%)",
      dataIndex: "rate",
      key: "rate",
      width: 200,
      ellipsis: true,
      align:'right',
      render: (text) => (_.isNumber(text) ? text : text || "-"),
    },
    {
      title: "持有该债券的基金",
      dataIndex: "holdBondFundList",
      key: "holdBondFundList",
      width: 180,
      ellipsis: true,
      render: (text) => {
        let str = "";
        if (!_.isEmpty(text)) {
          text.forEach((v, i) => {
            str =
              str +
              (v.fundName || "-") +
              `(${v.fundSecuCode || "-"})` +
              (i === text.length - 1 ? "" : ",");
          });
        }
        return str || "-";
      },
    },
  ];

  const tableClass = (arr: any, max?: number) =>
    cn({
      [styles.scrollTable]: true,
      hidden: arr?.length < 8,
      [styles.scrollTableFix]: max && arr?.length > max,
      [styles.empty]: _.isEmpty(arr),
    });

  const _patchCreditList = (arrList: any[] = [], len = 7) => {
    // console.log(arrList);
    if (arrList?.length > len) return arrList;
    const arr = new Array(len - arrList?.length).fill("").map((v, i) => {
      return {
        id: i,
      };
    });
    return arrList?.concat(arr);
  };

  return (
    <PageWrapper narrow minWidth="1068px">
      <Title style={{ marginLeft: 16, marginBottom: 12 }}>固收类资产特征</Title>
      <RenderDesc />
      <div className={cn(styles.investment)}>
        <LittleTitle title="各类型债券占债券投资比" />
        <EBox>
          {_.isEmpty(bondLegend) ? (
            <EventEmpty title="暂无数据" />
          ) : (
            <div style={{ height: 230 }}>
              <StackBar
                idName="overview-event"
                xAxis={bondAxis}
                legend={bondLegend}
                data={bondRatio}
                color={[...getBaseColors()]}
                percent={true}
              />
            </div>
          )}
        </EBox>
      </div>
      <div className={cn(styles.holderDetail, styles.mt12)}>
        <LittleTitle title="底层持仓明细(前20大持仓信用债)" />
        <div className={styles.holderDetail_table}>
          <Table
            className={cn(
              "list_table list_table_with_border table_header_center",
              styles.cusFixTable,
              detailList?.length > 20 ? styles.scrollTableConvertible : ""
            )}
            columns={detailColumns}
            dataSource={detailList}
            rowKey={(r) => r.bondInnerCode}
            pagination={false}
            style={{ whiteSpace: "nowrap" }}
            scroll={
              detailList?.length > 20
                ? { y: 560, x: window.innerWidth }
                : { x: true }
            }
          />
        </div>
      </div>
      <div className={cn(styles.holderDetail, styles.mt12)}>
        <LittleTitle title="底层持仓明细(可转债)" />
        <div className={styles.holderDetail_table}>
          <Table
            className={cn(
              "list_table list_table_with_border table_header_center",
              styles.cusFixTable,
              convertList?.length > 20 ? styles.scrollTableConvertible : ""
            )}
            columns={detailColumnsConvert}
            dataSource={convertList}
            rowKey={(r) => r.bondInnerCode}
            pagination={false}
            style={{ whiteSpace: "nowrap" }}
            scroll={
              convertList?.length > 20
                ? { y: 560, x: 1570 }
                : { x: 1570 }
            }
          />
        </div>
      </div>
      <div className={styles.pieTable}>
        <div className={styles.pieTable_left} key="credit">
          <LittleTitle title="已披露信用债行业分布" />
          <div className={styles.pieTable_left_body} key="credit-body">
            <div className={styles.echartsBarArea}>
              {creditList?.length > 0 ? (
                <Pie
                  name=""
                  idName="credit-pie"
                  legendData={creditList?.map((v) => v.firstIndustryName)}
                  pieData={creditPieData}
                  legendProps={{
                    right: "10%",
                    itemGap: 12,
                    top: `${
                      (100 -
                        (creditList?.length > 10 ? 10 : creditList?.length) *
                          10) /
                      2
                    }%`,
                  }}
                  pieStyle={{
                    width: "100%",
                    height: "100%",
                    radius: ["51%", "72%"],
                  }}
                  seriesType={{
                    left: "-13%",
                  }}
                  gridProps={{
                    top: "20%",
                    bottom: "0",
                  }}
                  formatLen={4}
                />
              ) : (
                <EventEmpty style={{ paddingTop: 72 }} title="暂无数据" />
              )}
            </div>
            <div className={styles.customTable}>
              <Table
                className={tableClass(creditList, 7)}
                columns={[
                  {
                    title: "行业分布",
                    dataIndex: "firstIndustryName",
                    key: "firstIndustryName",
                    width: 100,
                  },
                  {
                    title: "比例",
                    dataIndex: "ratioInNv",
                    key: "ratioInNv",
                    width: 100,
                    render: (text: number, records: any) => (
                      <span
                        style={{
                          textAlign: "right",
                          display: "block",
                          paddingRight: `calc(50% - ${
                            creditList[0]?.ratioInNv.toString()?.length * 4.5
                          }px)`,
                        }}
                      >
                        {records?.firstIndustryName ? text + "%" : ""}
                      </span>
                    ),
                  },
                ]}
                rowKey={(r) => r.id + "" + r.firstIndustryCode}
                dataSource={
                  creditList?.length > 0 ? _patchCreditList(creditList) : []
                }
                bordered
                scroll={creditList?.length > 7 ? { y: 195 } : {}}
                pagination={false}
              />
            </div>
          </div>
        </div>
        <div
          className={cn(styles.pieTable_left, styles.pieTable_right)}
          key="city"
        >
          <LittleTitle title="已披露城投债地区分布" />
          <div className={styles.pieTable_left_body} key="city-body">
            <div className={styles.echartsBarArea}>
              {areaList?.length > 0 ? (
                <Pie
                  name=""
                  idName="area-pie"
                  legendData={areaList?.map(
                    (v) =>
                      v.provinceName ||
                      PROVINCE_CODE_JSON[v.provinceCode + "0000"]
                  )}
                  pieData={areaPieData}
                  legendProps={{
                    right: "10%",
                    itemGap: 12,
                    top: `${
                      (100 -
                        (areaList?.length > 10 ? 10 : areaList?.length) * 10) /
                      2
                    }%`,
                  }}
                  pieStyle={{
                    width: "100%",
                    height: "100%",
                    radius: ["51%", "72%"],
                  }}
                  seriesType={{
                    left: "-13%",
                  }}
                  formatLen={4}
                />
              ) : (
                <EventEmpty style={{ paddingTop: 72 }} title="暂无数据" />
              )}
            </div>
            <div className={styles.customTable}>
              <Table
                className={tableClass(areaList, 7)}
                columns={[
                  {
                    title: "地区",
                    dataIndex: "provinceName",
                    key: "provinceName",
                    width: 100,
                    render: (text, record) =>
                      text || PROVINCE_CODE_JSON[record.provinceCode + "0000"],
                  },
                  {
                    title: "比例",
                    dataIndex: "ratioInNv",
                    key: "ratioInNv",
                    width: 100,
                    render: (text: number, records: any) => (
                      <span
                        style={{
                          textAlign: "right",
                          display: "block",
                          // paddingRight:20
                          paddingRight: `calc(50% - ${
                            areaList[0].ratioInNv.toString()?.length * 4.5
                          }px)`,
                        }}
                      >
                        {records?.provinceName || records.provinceCode
                          ? text + "%"
                          : ""}
                      </span>
                    ),
                  },
                ]}
                rowKey={(r) => r.id + r.provinceCode}
                dataSource={
                  areaList?.length > 0 ? _patchCreditList(areaList) : []
                }
                bordered
                scroll={areaList?.length > 7 ? { y: 195 } : {}}
                pagination={false}
              />
            </div>
          </div>
        </div>
      </div>

      <div className={styles.lineTable}>
        <LittleTitle
          title="基金组合加权久期"
          weight={600}
          subWeight={400}
          secTitle=" - 衡量基金组合的加权久期的变化"
        />
        <div className={styles.lineTable_content}>
          <div className={styles.lineTable_content_chart}>
            {_.isEmpty(weightLine?.xaxis) ? (
              <EventEmpty style={{ paddingTop: 104 }} title="暂无数据" />
            ) : (
              <MultiLine
                idName="comp-event"
                xAxis={weightLine?.xaxis || []}
                legend={weightLine?.yaxis?.map((v) => v.label)}
                data={weightLine?.yaxis || []}
                color={["#3457C4", "#E85C36", "#748295"]}
                // formatLen={16}
              />
            )}
          </div>
          <div className={cn(styles.lineTable_content_table)}>
            <Table
              className={cn(tableClass(areaList, 8))}
              columns={[
                {
                  title: "时间",
                  dataIndex: "endDate",
                  key: "endDate",
                  width: 100,
                },
                {
                  title: "组合久期",
                  dataIndex: "portfolioWeightingDuration",
                  key: "portfolioWeightingDuration",
                  width: 100,
                  render: (text, records) =>
                    _renderText(text, records, "endDate"),
                },
                {
                  title: (
                    <div className={styles.tableHeader}>
                      <p>半年度收益率前1/4</p>
                      <p>中长期纯债基金久期均值</p>
                    </div>
                  ),
                  dataIndex: "mediumAndLongDuration",
                  key: "mediumAndLongDuration",
                  width: 200,
                  render: (text, records) =>
                    _renderText(text, records, "endDate"),
                },
                {
                  title: (
                    <div className={styles.tableHeader}>
                      <p>半年度收益率前1/4</p>
                      <p>短债纯债基金久期均值</p>
                    </div>
                  ),
                  dataIndex: "shortDuration",
                  key: "shortDuration",
                  width: 200,
                  render: (text, records) =>
                    _renderText(text, records, "endDate"),
                },
              ]}
              rowKey={(r) => r.id}
              dataSource={
                weightList?.length > 0 ? _patchCreditList(weightList, 8) : []
              }
              bordered
              scroll={areaList?.length > 8 ? { y: 222 } : {}}
              pagination={false}
            />
          </div>
        </div>
      </div>
    </PageWrapper>
  );
};

export default FixedAssets;
